<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="所属分类" prop="no">
          <el-select v-model="queryParams.parentId" placeholder="全部"  clearable style="width: 200px">
            <el-option
                v-for="(name, id) in parentCategoryMap"
                :key="id"
                :label="name"
                :value="id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="全部" clearable class="!w-[100px]">
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="物料编码" prop="no">
          <el-input
              v-model="queryParams.no"
              placeholder="物料编码"
              clearable
              @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item label="物料名称" prop="name">
          <el-input
              v-model="queryParams.name"
              placeholder="物料名称"
              clearable
              @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon>
              <Search/>
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh/>
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
            v-hasPerm="['system:lpsWl:add']"
            type="success"
            @click="handleOpenDialog()"
        >
          <template #icon>
            <Plus/>
          </template>
          新增
        </el-button>
        <el-button
            v-hasPerm="['system:lpsWl:delete']"
            type="danger"
            :disabled="removeIds.length === 0"
            @click="handleDelete()"
        >
          <template #icon>
            <Delete/>
          </template>
          删除
        </el-button>
      </div>

      <el-table
          ref="dataTableRef"
          v-loading="loading"
          :data="pageData"
          highlight-current-row
          border
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column type="index" label="序号" width="70" align="center"/>
        <el-table-column
            key="no"
            label="物料编码"
            prop="no"
            width="250"
            align="center"
            :show-overflow-tooltip="true"
        />
        <el-table-column
            key="name"
            label="物料名称"
            prop="name"
            min-width="300"
            align="center"
            :show-overflow-tooltip="true"
        />
        <el-table-column
            key="parentId"
            label="所属分类"
            prop="parentId"
            min-width="150"
            align="center">
          <template #default="scope">
            {{ parentCategoryMap[scope.row.parentId] || '未知分类' }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">
              {{ scope.row.status == 1 ? "已启用" : "未启用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
            key="remark"
            label="备注"
            prop="remark"
            min-width="150"
            align="center"
            :show-overflow-tooltip="true"
        />
        <el-table-column fixed="right" label="操作" width="220" align="center">
          <template #default="scope">
            <el-button
                v-hasPerm="['system:lpsWl:edit']"
                type="primary"
                size="small"
                link
                @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon>
                <Edit/>
              </template>
              编辑
            </el-button>
            <el-button
                v-hasPerm="['system:lpsWl:delete']"
                type="danger"
                size="small"
                link
                @click="handleDelete(scope.row.id)"
            >
              <template #icon>
                <Delete/>
              </template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleQuery()"
      />
    </el-card>

    <!-- 物料表单弹窗 -->
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="500px"
        @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="物料编码" prop="no">
          <el-input
              v-model="formData.no"
              placeholder="物料编码"
          />
        </el-form-item>

        <el-form-item label="物料名称" prop="name">
          <el-input
              v-model="formData.name"
              placeholder="物料名称"
          />
        </el-form-item>

        <el-form-item label="所属分类" prop="parentId">
          <el-select v-model="formData.parentId" placeholder="请选择所属分类" clearable style="width: 100%">
            <el-option
                v-for="(name, id) in parentCategoryMap"
                :key="id"
                :label="name"
                :value="id"
            />
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="状态(1-是 0-否)" prop="status">-->
        <!--          <el-input-->
        <!--              v-model="formData.status"-->
        <!--              placeholder="状态(1-是 0-否)"-->
        <!--          />-->
        <!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "LpsWl",
  inheritAttrs: false,
});

import LpsWlAPI, {LpsWlForm, LpsWlPageQuery, LpsWlPageVO} from "@/api/system/lps-wl";

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<LpsWlPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 物料表格数据
const pageData = ref<LpsWlPageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 物料表单数据
const formData = reactive<LpsWlForm>({});

// 物料表单校验规则
const rules = reactive({
  no: [{required: true, message: "请输入物料编码", trigger: "blur"}],
  name: [{required: true, message: "请输入物料名称", trigger: "blur"}],
});

const parentCategoryMap = {
  1: "触动机构",
  2: "触动机构+C",
  3: "新产品 线",
  4: "新产品",
  5: "配件",
  6: "永乐/利居"
};

/** 查询物料 */
function handleQuery() {
  loading.value = true;
  LpsWlAPI.getPage(queryParams)
      .then((data) => {
        pageData.value = data.list;
        total.value = data.total;
      })
      .finally(() => {
        loading.value = false;
      });
}

/** 重置物料查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  queryParams.parentId = null;
  queryParams.status = null;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开物料弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改物料";
    LpsWlAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增物料";
  }
}

/** 提交物料表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        LpsWlAPI.update(id, formData)
            .then(() => {
              ElMessage.success("修改成功");
              handleCloseDialog();
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
      } else {
        LpsWlAPI.add(formData)
            .then(() => {
              ElMessage.success("新增成功");
              handleCloseDialog();
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭物料弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除物料 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
      () => {
        loading.value = true;
        LpsWlAPI.deleteByIds(ids)
            .then(() => {
              ElMessage.success("删除成功");
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
      },
      () => {
        ElMessage.info("已取消删除");
      }
  );
}

onMounted(() => {
  handleQuery();
});
</script>

<style scoped>
:deep(.el-input-number .el-input__inner) {
  text-align: left !important;
}

:deep(.el-popper) {
  max-width: 300px;
}
</style>
